//
//  OAuthViewController.swift
//  weiboxiangmu
//
//  Created by wei_jingyun on 15/6/26.
//  Copyright © 2015年 wei_jingyun. All rights reserved.
//

import UIKit
import AFNetworking

class OAuthViewController: UIViewController , UIWebViewDelegate {
    // ID 回调地址 Secret
    private let wb_client_id    = "1186548779"
    private let wb_redirect_uri = "https://www.baidu.com"
    private let wb_app_secret   = "fbe745a0c91c5aed2f819f97529ff2bc"
    
//    private let wb_client_id    = "1977290820"
//    private let wb_redirect_uri = "https://www.baidu.com"
//    private let wb_app_secret   = "86edeb7298f13d7f23ef36611f973400"
    
    // 加载授权页面 webView
    var webView: UIWebView?
    // 是不是登陆
    var login = true
    
    override func loadView() {
        webView = UIWebView()
        view = webView
        title = "新浪微博"
        // 左边按钮返回
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    /// 是navigationItem的leftBut调用不能使用私有
     func close() {
        JYdisMiss
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        let urlString = login ? "https://api.weibo.com/oauth2/authorize?client_id=\(wb_client_id)&redirect_uri=\(wb_redirect_uri)" :  "https://m.weibo.cn/reg/index?jp=1&wm=4406&appsrc=1UrtDt&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D1186548779%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttps%253A%252F%252Fwww.baidu.com%26from%3D%26with_cookie%3D"
        
        Debug.Log("urlString")
        let url = NSURL(string: urlString)!
        webView?.loadRequest(NSURLRequest(URL: url))
        webView?.delegate = self
    }
    
    // 是否加载网页请求
    // 授权返回  https://www.baidu.com/?code=3e9b9eb33b46509fde5f997210dac498
    // 取消返回  https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        // 1.获取网络请求的 url
        let urlString = request.URL!.absoluteString
        Debug.Log(urlString)
        
        // 2.判断是否是回调url hasPrefix 判断是不是前缀 不是就加载
        if !(urlString.hasPrefix(wb_redirect_uri)) {
            return true
        }
    
        // 3.是回调就找出获取codeID
        let query = request.URL!.query! // code=4442d4aaf86134eb3963276aa22a544b
        let codeStr = "code="
        // 如果前缀包含 codeStr 则后面的就是codeID
        if query.hasPrefix(codeStr){
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            Debug.Log("code = \(code)") // 1778ae8010ffec52cd004cbd26105c5a
            
            // MARK:更跟据授权码获取 access_token
            getAccesstoken(code)
            
        }else {
            // 取消授权关闭窗口
            close()
        }
        
        return false
    }
    
    /// 开始加载
    func webViewDidStartLoad(webView: UIWebView){
        JYShow
    }
    
    /// 结束加载
    func webViewDidFinishLoad(webView: UIWebView){
        JYdisMiss
    }
    
    /// 加载错误
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?){
        JYdisMiss
        JYShow
        Debug.Log("错误\(error)")
    }
    
    func getAccesstoken(codeId : String){
        // 1. url
        let UrlString = "oauth2/access_token"
        
        // 2.请求参数
        let params = ["client_id" : wb_client_id ,
            "client_secret"	: wb_app_secret ,
            "grant_type" :	"authorization_code",
            "code"	: codeId ,
            "redirect_uri" : wb_redirect_uri ]
        
        NetWorkTools.sharedNetWorkTools().POST(UrlString, parameters: params, success: { (_ , JSON ) -> Void in
            Debug.Log(JSON)
            // 必须指定 字典类型
            UserAccount(dict: JSON as! [String : AnyObject]).loadUserInfo({ (account, error) -> () in
                
                if account == nil {
                    Debug.Log(error!)
                    JYNetError
                    return
                }
                
                // 切换界面  false 就进入欢迎界面
                NSNotificationCenter.defaultCenter().postNotificationName(JYSwitchRootVCNotification, object: false)
                
                //关闭当前控制器
                self.close()
            })

            }) { (_ , error) -> Void in
                Debug.Log(error)
                JYNetError
        }
        
    }

}
